package com.xuecheng.manage_cms_client.mq;

import com.alibaba.fastjson.JSON;
import com.xuecheng.framework.domain.cms.CmsPage;
import com.xuecheng.manage_cms_client.dao.CmsPageRepository;
import com.xuecheng.manage_cms_client.service.PageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import springfox.documentation.spring.web.json.Json;

import java.util.Map;
import java.util.Optional;

/**
 * @author: gongfy
 * @create: 2020/7/16 14:32
 * @Description: 发布页面的消费客户端:监听页面发布队列的消息，收到消息(中包含pageId)后从mongodb下载文件，保存在本地
 */
@Component
@Slf4j
public class ConsumerPostPage {
    @Autowired
    private CmsPageRepository cmsPageRepository;
    @Autowired
    private PageService pageService;

    @RabbitListener(queues = {"${xuecheng.mq.queue}"}) // 监听队列
    public void receviPostMessage(String msg){
        //解析消息为map
        Map map = JSON.parseObject(msg, Map.class);
        log.info("receive msg post page:{}",map);
        //取出页面id
        String pageId = String.valueOf(map.get("pageId"));
        //查询页面信息 todo 作用是干啥
        Optional<CmsPage> cmsPageOptional = cmsPageRepository.findById(pageId);
        if (!cmsPageOptional.isPresent()){
            log.error("receive cms post page,cmsPage is null:{}",map.toString());
            return;
        }
        //消费方根据消息中的pageId从mongodb数据库下载页面到本地
        pageService.saveHtmlToPhysicalPath(pageId);
    }
}
